#include "OneginSort.h"



int main()
{
    setlocale(LC_ALL, "rus");

    FILE* f = fopen("o.txt", "r");
    int n = 0;
    char** Strings = bufferize(f, &n);

    fclose(f);

    qsort(Strings, n, sizeof(*Strings), comparePLEASE);

    if (!(f = fopen("OsortedAlph.txt", "w+")))
    {printf("Unable to open OsortedAlph"); abort();}

    for(int i = 0; i < n; fprintf(f,"%s\n", Strings[i++]));
    fclose(f);

    for(int i = 0; i < n; strrev(Strings[i++]));
    qsort(Strings, n, sizeof(*Strings), comparePLEASE);
    for(int i = 0; i < n; strrev(Strings[i++]));

    if (!(f = fopen("OsortedRithm.txt", "w+")))
    {printf("Unable to open OsortedRithm"); abort();}
    for(int i = 0; i < n; fprintf(f,"%s\n", Strings[i++]));
    fclose(f);

    return 0;
}
int CountOf(const   char *str, int length,   char ch)
{
    int counter = 0;
    for (int i = 0; i < length; i++)
        if (str[i] == ch) counter++;
    return counter;
}

void swapIn(  char* str,   char a,   char b, int len)
{
    int counter = 0;
    for (int i = 0; i < len; i++)
    {
        if (*(str + i) == a) *(str + i) = b;
        str++;
    }
}
int makeStrings(char** Strings,   char* buffer, int length)
{
    int n = 1;
    Strings[0] = buffer;
    for(int i = 1; i < length; i++)
        if(buffer[i] == '\n')
        {
            Strings[n] = buffer + i + 1;
            buffer[i] = 0;
            n++;
        }

    return n;
}

int comparePLEASE(const void* a, const void* b)
{
    return strcmp(*(const char**) a, *(const char**) b);
}
void swap(char* a, char* b)
{
    if (a != NULL && b != NULL)
    {
        char temp = *b;
        *b = *a;
        *a = temp;
    }
    else
    {
        printf("\n ERROR: Null pointers in swap(char*, char*)");
        abort();
    }
}

char** bufferize(FILE* f, int* n)
{
    if (f == NULL)
    {
        printf("\n ERROR: Null pointer in bufferize(FILE*)");
        abort();
    }
    int fileLength = filelength(fileno(f));

    char* buffer = (char*) calloc(fileLength + 1, sizeof(char));
    *(buffer + fileLength) = 0;

    fread(buffer, fileLength, sizeof(char), f);
    fclose(f);

    int lineCount = CountOf(buffer, fileLength, '\n') + 1;
    printf("%d\n", lineCount);
    char** Strings = (char**) calloc(lineCount, sizeof(char*));

    *n = makeStrings(Strings, buffer, fileLength);
    return Strings;
}
